<template>
    <div v-loading="loading" class="monthPlanAdd">
        <div class="pub-detail-title-btn">
            <template v-if="state !== 3">
                <a-button v-if="!isContract" type="primary" @click="openDailog"> 添加行 </a-button>
                <a-button v-if="!isContract" @click="handleDel"> 删除行 </a-button>
            </template>
            <excel ref="exportSelect" file-name="物资合同评审物资明细" is-click-generate="false">
                <a-button slot="excelBtn" @click="exportSelect"> 导出选中 </a-button>
            </excel>
            <excel ref="exportAll" file-name="物资合同评审物资明细" is-click-generate="false">
                <a-button slot="excelBtn" @click="exportAll"> 导出全部 </a-button>
            </excel>
        </div>
        <a-table
            ref="table"
            :pagination="false"
            :columns="state !== 3 ? columns : columnsLook"
            :data-source="data"
            bordered
            class="bgFFF"
            :scroll="{ x: 1300 }"
            row-key="id"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
            <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
            <template
                v-for="col in [
                    'number',
                    'settleAmount',
                    'sumSettle',
                    'controlAmount',
                    'sumTotal',
                    'settlePrice',
                    'contractPrice',
                    'sumSettleControlDiff',
                    'sumSettleControl',
                    'sumUnitPoint',
                    'remark'
                ]"
                :slot="col"
                slot-scope="text, record, index"
            >
                <div :key="col">
                    <template v-if="record.editable">
                        <BaseInput
                            v-if="col === 'remark'"
                            style="margin: -5px 0"
                            :value="text"
                            :disabled="
                                col === 'sumSettle' ||
                                col === 'sumTotal' ||
                                col === 'sumSettleControlDiff' ||
                                col === 'sumSettleControl' ||
                                col === 'sumUnitPoint'
                            "
                            @blur="(e) => handleChange(e.target.value, record.id, col)"
                        />

                        <BaseInputNumber
                            v-else-if="col === 'number'"
                            :precision="0"
                            style="margin: -5px 0"
                            :value="text"
                            :disabled="
                                col === 'sumSettle' ||
                                col === 'sumTotal' ||
                                col === 'sumSettleControlDiff' ||
                                col === 'sumSettleControl' ||
                                col === 'sumUnitPoint'
                            "
                            @change="(e) => handleChange(e, record.id, col)"
                            @blur="(e) => handleChange(e.target.value, record.id, col)"
                        />
                        <BaseInputNumber
                            v-else
                            :precision="2"
                            style="margin: -5px 0"
                            :value="text"
                            :disabled="
                                col === 'sumSettle' ||
                                col === 'sumTotal' ||
                                col === 'sumSettleControlDiff' ||
                                col === 'sumSettleControl' ||
                                col === 'sumUnitPoint'
                            "
                            @change="(e) => handleChange(e, record.id, col)"
                            @blur="(e) => handleChange(e.target.value, record.id, col)"
                        />
                    </template>
                    <template v-else>
                        {{ col === 'analysisIdentify' ? record.analysisIdentifyStr : text }}
                    </template>
                </div>
            </template>
            <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                    <span v-if="record.editable && state !== 3">
                        <a @click="() => save(record.id)">保存</a>
                        <a @click="cancel(record.id)">取消</a>
                    </span>
                    <span v-else>
                        <a :disabled="editingKey !== ''" @click="() => edit(record.id)">编辑</a>
                    </span>
                </div>
            </template>
        </a-table>
        <pagination
            v-model="pageNo"
            :total="totalSize"
            :page-size.sync="pageSize"
            @change="handlePageChange"
            @showSizeChange="showSizeChange"
        />
        <!--        <signCodeMaterialList ref="detailDialog" :other-data="{ countersignId: row.countersignId}"-->
        <!--                              @createList="createList"></signCodeMaterialList>-->
        <!--        <material-list ref="detailDialog"-->
        <!--                       :url-fun="materialsMainList"-->
        <!--                       :params="{ countersignId: row.countersignId}"-->
        <!--                       @createList="createList"></material-list>-->
        <material-list ref="detailDialog" @createList="createList" />
    </div>
</template>
<script>
import { materialsList, materialsAdd, materialsEdit, materialsDel } from '@/api/material/contract/review'
import { materialsMainList } from '@/api/material/procurement/sign'

const data = []
export default {
    name: 'RebarPlan',
    props: {
        state: {
            type: Number
        },
        isContract: {
            type: Boolean,
            default: false
        },
        row: {
            type: Object,
            default: () => {
                return null
            }
        }
    },
    data() {
        this.cacheData = data.map((item) => ({ ...item }))
        return {
            materialsMainList: materialsMainList,
            loading: false,
            selectedRows: [],
            pageNo: 1,
            pageSize: 10,
            queryParam: {},
            totalSize: 0,
            selectedRowKeys: [],
            columns: [
                {
                    title: '序号',
                    width: 70,
                    scopedSlots: { customRender: 'index' }
                },
                {
                    title: '物资名称',
                    width: 120,
                    dataIndex: 'materialName'
                },
                {
                    title: '物料编码',
                    width: 120,
                    dataIndex: 'materialCode'
                },
                {
                    title: '规格型号',
                    width: 120,
                    dataIndex: 'materialModel'
                },
                {
                    title: '单位',
                    width: 80,
                    dataIndex: 'materialUnit'
                },
                {
                    title: '数量',
                    width: 140,
                    dataIndex: 'number',
                    scopedSlots: { customRender: 'number' }
                },
                {
                    title: '发包人结算单价（元）',
                    width: 140,
                    dataIndex: 'settlePrice',
                    scopedSlots: { customRender: 'settlePrice' }
                },
                {
                    title: '发包人结算金额（元）',
                    width: 140,
                    dataIndex: 'sumSettle',
                    scopedSlots: { customRender: 'sumSettle' }
                },
                {
                  title: '合同单价(税前)(元)',
                    width: 140,
                    dataIndex: 'contractPrice',
                    scopedSlots: { customRender: 'contractPrice' }
                },
                {
                    title: '合同金额（元）',
                    width: 140,
                    dataIndex: 'sumTotal',
                    scopedSlots: { customRender: 'sumTotal' }
                },
                {
                    title: '结算单价与合同单价差（元）',
                  width: 160,
                    dataIndex: 'sumSettlContractDiff',
                    scopedSlots: { customRender: 'sumSettlContractDiff' }
                },
                {
                    title: '结算金额与合同金额差（元）',
                    width: 140,
                    dataIndex: 'sumSettleContract',
                    scopedSlots: { customRender: 'sumSettleContract' }
                },
                {
                    title: '价差比例',
                    width: 140,
                    dataIndex: 'sumUnitPoint',
                    scopedSlots: { customRender: 'sumUnitPoint' }
                },
                {
                    title: '备注',
                    width: 140,
                    dataIndex: 'remark',
                    scopedSlots: { customRender: 'remark' }
                },
                {
                    title: '操作',
                    width: 120,
                    fixed: 'right',
                    dataIndex: 'operation',
                    scopedSlots: { customRender: 'operation' }
                }
            ],
            columnsLook: [
                {
                    title: '序号',
                    width: 70,
                    scopedSlots: { customRender: 'index' }
                },
                {
                    title: '物资名称',
                    width: 120,
                    dataIndex: 'materialName'
                },
                {
                    title: '物料编码',
                    width: 120,
                    dataIndex: 'materialCode'
                },
                {
                    title: '规格型号',
                    width: 120,
                    dataIndex: 'materialModel'
                },
                {
                    title: '单位',
                    width: 80,
                    dataIndex: 'materialUnit'
                },
                {
                    title: '数量',
                    width: 140,
                    dataIndex: 'number',
                    scopedSlots: { customRender: 'number' }
                },
                {
                    title: '发包人结算单价（元）',
                    width: 140,
                    dataIndex: 'settlePrice',
                    scopedSlots: { customRender: 'settlePrice' }
                },
                {
                    title: '发包人结算金额（元）',
                    width: 140,
                    dataIndex: 'sumSettle',
                    scopedSlots: { customRender: 'sumSettle' }
                },
              {
                title: '合同单价(税前)(元)',
                width: 160,
                dataIndex: 'contractPrice',
                scopedSlots: { customRender: 'contractPrice' }
              },
                {
                    title: '合同金额（元）',
                    width: 140,
                    dataIndex: 'sumTotal',
                    scopedSlots: { customRender: 'sumTotal' }
                },
                {
                    title: '结算单价与合同单价差（元）',
                    width: 140,
                    dataIndex: 'sumSettlContractDiff',
                    scopedSlots: { customRender: 'sumSettlContractDiff' }
                },
                {
                    title: '结算金额与合同金额差（元）',
                    width: 140,
                    dataIndex: 'sumSettleContract',
                    scopedSlots: { customRender: 'sumSettleContract' }
                },
                {
                    title: '价差比例',
                    width: 140,
                    dataIndex: 'sumUnitPoint',
                    scopedSlots: { customRender: 'sumUnitPoint' }
                },
                {
                    title: '备注',
                    width: 140,
                    dataIndex: 'remark',
                    scopedSlots: { customRender: 'remark' }
                }
            ],
            editingKey: '',
            data: [],
            selectedId: [],
            rules: {
                number: [{ rule: 'required', message: '数量不能为空' }],
                settlePrice: [{ rule: 'required', message: '发包人结算单价不能为空' }],
                contractPrice: [{ rule: 'required', message: '招标控制单价不能为空' }]
            }
        }
    },
    computed: {
        rowSelection() {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
                },
                getCheckboxProps: (record) => {
                    return { props: { disabled: record.id === '693023867177930752', name: record.name } }
                }
            }
        }
    },
    mounted: function () {
        if (this.state === 3) {
            this.editingKey = true
        }
        this.list()
        this.initErrMessage(this.rules)
        this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
        this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    },
    methods: {
        exportSelect: function () {
            if (this.selectedRowKeys.length > 0) {
                this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
            } else {
                this.$message.warning('请选择需要导出的数据')
            }
        },
        exportAll: function () {
            // 参数：查询条件、导出的回调
            if (this.totalSize) {
                this.pageNo = 1
                this.list(this.$refs.exportAll.setDataAndGenerate)
            } else {
                this.$message.warning('没有可导出的数据')
            }
        },
        createList: function (selectRow) {
            let params = {
                // materialName: selectRow.materialName,
                // materialCode: selectRow.materialCode,
                // materialModel: selectRow.materialModel,
                materialName: selectRow.name,
                materialCode: selectRow.code,
                materialModel: selectRow.specificationModel,
                unit: selectRow.unitId,
                materialContractId: this.row.id,
                number: '',
                settlePrice: '',
                sumSettle: '',
                contractPrice: '',
                sumTotal: '',
                sumSettlContractDiff: '',
                sumSettleContract: '',
                sumUnitPoint: '',
                remark: '',
                // materialId: selectRow.materialId
                materialId: selectRow.id
            }
            materialsAdd(params).then((res) => {
                if (res.code === 200) {
                    this.list()
                }
            })
        },
        openDailog: function () {
            if (this.editingKey !== '') {
                this.$message.error('新增前请结束当前操作行')
                return
            }
            this.$refs.detailDialog.open()
        },
        // 删除
        handleDel() {
            this.delList(
                materialsDel,
                () => {
                    this.initTable()
                    this.selectedId = []
                    this.selectedRowKeys = []
                    this.selectedRows = []
                    this.editingKey = ''
                },
                { ids: this.selectedId }
            )
        },
        initTable() {
            this.pageNo = 1
            this.list()
        },
        list(callback) {
            this.loading = true
            materialsList({
                pageSize: callback ? this.totalSize : this.pageSize,
                pageNo: this.pageNo,
                id: this.row.id
            }).then((res) => {
                if (res.code === 200) {
                    if (callback) {
                        if (res.data.length) {
                            callback(res.data)
                        } else {
                            this.$message.warning('没有可导出的数据')
                        }
                        this.loading = false
                        return
                    }
                    this.data = res.data
                    this.totalSize = res.totalSize
                    this.cacheData = res.data.map((item) => ({ ...item }))
                }
                this.loading = false
            })
        },
        handleChange(value, key, column) {
            const newData = [...this.data]
            const target = newData.filter((item) => key === item.id)[0]
            let sumTotal = ''
            if (target) {
                target[column] = value
                target['sumSettle'] = target['number'] * target['settlePrice']
                target['sumTotal'] = target['number'] * target['contractPrice']
                target['sumSettlContractDiff'] = target['settlePrice'] - target['contractPrice']
                target['sumSettleContract'] = target['sumSettle'] - target['sumTotal']
                target['sumSettleContract'] = target['sumSettleContract'].toFixed(2)
                target['sumUnitPoint'] = target['sumSettleContract'] / target['sumSettle']
                target['sumUnitPoint'] = target['sumUnitPoint'].toFixed(2)

                if (target['sumSettle'] < target['sumTotal']) {
                    this.$noticeWarning('发包人结算金额必须大于合同金额')
                    return
                }
                newData.map(function (item) {
                    sumTotal += item.sumTotal
                })
                if (this.rules[column]) {
                    this.customValidation(value, column)
                }
                this.data = newData
                this.$emit('getTotal', { sumTotal: sumTotal })
            }
        },
        edit(key) {
            const newData = [...this.data]
            const target = newData.filter((item) => key === item.id)[0]
            this.editingKey = key
            if (target) {
                target.editable = true
                this.data = newData
                console.log(target.editable)
            }
        },
        handlePageChange(pageNo, pageSize) {
            this.pageNo = pageNo
            this.list()
            this.selectedRowKeys = []
        },
        showSizeChange(pageNo, pageSize) {
            this.pageSize = pageSize
            this.initTable()
        },
        async save(key) {
            // 编辑保存
            const newData = [...this.data]
            const newCacheData = [...this.cacheData]
            const target = newData.filter((item) => key === item.id)[0]
            if (target['sumSettle'] < target['sumTotal']) {
                this.$noticeWarning('发包人结算金额必须大于合同金额')
                return
            }
            for (let key in target) {
                if (this.rules[key]) {
                    this.customValidation(target[key], key)
                }
            }
            for (let i in this.customValidationErr) {
                if (i) {
                    return
                }
            }
            this.loading = true
            let res = await materialsEdit(target)
            if (res.code === 200) {
                this.$message.success('编辑成功')
                this.initTable()
            }
            this.loading = false
            const targetCache = newCacheData.filter((item) => key === item.id)[0]
            if (target && targetCache) {
                delete target.editable
                this.data = newData
                Object.assign(targetCache, target)
                this.cacheData = newCacheData
            }
            this.editingKey = ''
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedId = []
            selectedRows.map((i) => {
                this.selectedId.push(i.id)
            })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        cancel(key) {
            const newData = [...this.data]
            const target = newData.filter((item) => key === item.id)[0]
            this.editingKey = ''
            this.planDate = null
            this.selectVal = null
            if (target) {
                Object.assign(target, this.cacheData.filter((item) => key === item.id)[0])
                // target.editable = false;
                delete target.editable
                this.data = newData
            }
        }
    }
}
</script>
